<!--
 * @Author: yangzhiyu yangzhiyu@mail.pigcms.com
 * @Date: 2024-03-29 16:56:47
 * @LastEditors: yangzhiyu yangzhiyu@mail.pigcms.com
 * @LastEditTime: 2024-04-01 17:03:57
 * @FilePath: \fe_user_pc\src\views\shotstack\MuseMixedCut\MixedCutPreview\components\saveVideoDialog.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
    查看预览视频
-->
<script setup>
import baseModel from "@/components/baseModel/baseModel.vue";
import { computed, nextTick, onMounted, ref } from "vue";
// 绘制视频帧函数
import { splitVideo, splitAndDrawVideoFrames } from '../../utools/index.js'
const dialog = ref(null);

const emit = defineEmits(["changeVideoData:data"])

// 视频信息
const viewTargetVideo = ref({})
// 视频链接
const videoUrl = ref('')
const showModal = (data) => {
    dialog.value.showModal();
    console.log(data, '打开的视频链接');
    videoUrl.value = !!data?.url
        ? data?.url + '?v=' + (new Date()).valueOf()
        : data.material_url + '?v=' + (new Date()).valueOf()

    videoDuration.value = data.material_duration
    viewTargetVideo.value = JSON.parse(JSON.stringify(data))
    if (data.start_time != 0 || data.end_time != data.material_duration) {
        echoData({
            start_time: data.start_time,
            end_time: data.end_time
        })
    } else {
        containerWidth.value = 1100
        containerLeft.value = 0
    }
    // 存放视频的信息
    nextTick(() => {
        initCanvas()
        // 绘制视频帧
        splitAndDrawVideoFrames({
            videoId: '#videoElement',
            canvasId: '#canvasElement',
            videoUrl: videoUrl.value,
            maxFrameHeight: 36, // 假设我们希望每个帧的最大高度
            canvasWidth: 1100, // Canvas的总宽度
        });
    });
};

// 重新回显修改的左右进度条
const echoData = (data) => {
    const pixelsPerSecond = videoDuration.value / 1100;
    const echoContainerLeft = data.start_time / pixelsPerSecond;
    const echoContainerWidth = (data.end_time - data.start_time) / pixelsPerSecond;
    containerWidth.value = echoContainerWidth
    containerLeft.value = echoContainerLeft
}

const showVideo = ref(null)

const save = () => {
    console.log('保存视频')
    // viewTargetVideo.value
    console.log(viewTargetVideo.value, '保存视频的信息');
    // 赋值开始和结束时间
    viewTargetVideo.value.start_time = calculateTimeRange.value.startTime
    viewTargetVideo.value.end_time = calculateTimeRange.value.endTime
    emit('changeVideoData', viewTargetVideo.value)
    closeModal()
}

const reset = () => {
    // 重置切割进度, 重置视频的进度
    // containerWidth.value = 1090
    // containerLeft.value = 0
    echoData({
        start_time: viewTargetVideo.value.start_time,
        end_time: viewTargetVideo.value.end_time
    })
    showVideo.value.pause()
    showVideo.value.currentTime = 0
}

// 绘制canvas刻度
const initCanvas = () => {
    // debugger
    return
    console.log('执行了刻度');
    // 获取 canvas 元素及其上下文
    var canvas = document.getElementById('rulerCanvas');
    var ctx = canvas.getContext('2d');
    // 设定 canvas 的宽度和高度以铺满容器
    canvas.width = canvas.offsetWidth;
    canvas.height = 30; // 设定一个固定的高度
    var width = canvas.width;
    var height = canvas.height;
    // 刻度数量，更多刻度会使得间隔更短
    var totalTicks = 80;
    // 时间标签数量
    var timeStamps = 8;
    // 设定每个刻度的间隔
    var tickInterval = width / totalTicks;
    var timeStampInterval = width / timeStamps;

    // 画上方的线条
    ctx.beginPath();
    ctx.moveTo(0, 1);
    ctx.lineTo(width, 1);

    // 绘制刻度
    for (var i = 0; i <= totalTicks; i++) {
        ctx.moveTo(tickInterval * i, 0);
        ctx.lineTo(tickInterval * i, height / 5); // 刻度的长度为canvas的高度的四分之一
    }

    // 时间标签
    for (var j = 0; j < timeStamps; j++) {
        var xPosition = timeStampInterval * j + timeStampInterval / 2; // 将时间标签居中放置在间隔位置

        // 添加时间文本，这里只是示例，你需要根据实际情况来格式化时间
        var text = `时间${j + 1}`;
        var textWidth = ctx.measureText(text).width;
        var textX = xPosition - textWidth / 2; // 计算文本x位置
        var textY = height / 8 + 20; // 调整文本y位置，留出足够空间以防止文字挤压
        ctx.fillStyle = '#7a7a7a'; // 文字颜色
        // 绘制文本
        ctx.fillText(text, textX, textY);
    }

    // 设置线条样式
    ctx.strokeStyle = '#7a7a7a'; // 黑色线条
    ctx.lineWidth = 1; // 线宽为1px
    ctx.stroke();

    // 结束绘制路径
    ctx.closePath();
}


// 初始容器宽度和拖拽状态
const containerWidth = ref(1100);
// 当前元素定位的左侧
const containerLeft = ref(0);
let isResizing = false;
let startWidth = 0;
let startLeft = 0;
let startX = 0;
const handelMousedown = (event, direction) => {
    // 防止选中文本
    event.preventDefault();
    isResizing = true;
    startX = event.clientX;
    startWidth = containerWidth.value;
    startLeft = containerLeft.value;

    const maxWidth = 1100; // 假设这是父元素的最大宽度

    const doResize = (moveEvent) => {
        if (!isResizing) return;
        const dx = moveEvent.clientX - startX;

        if (direction === 'right') {
            let newWidth = startWidth + dx;
            // 确保新宽度不会小于最小宽度
            const minWidth = 50;
            // 如果新宽度加上左侧定位超过最大宽度，则限制它
            if (newWidth + startLeft > maxWidth) {
                newWidth = maxWidth - startLeft;
            } else if (newWidth < minWidth) { // 如果新宽度小于最小宽度，则设置为最小宽度
                newWidth = minWidth;
            }
            containerWidth.value = newWidth;
        } else {
            // 左侧拖拽逻辑
            const newWidth = startWidth - dx;
            if (newWidth > 50 && (startLeft + dx) >= 0) {
                containerWidth.value = newWidth;
                containerLeft.value = startLeft + dx;
            }
        }
    };

    const stopResize = () => {
        isResizing = false;
        window.removeEventListener('mousemove', doResize);
        window.removeEventListener('mouseup', stopResize);
    };

    // 监听鼠标移动和松开事件
    window.addEventListener('mousemove', doResize);
    window.addEventListener('mouseup', stopResize);
}

// 计算框选的范围
// 假设的视频时长
const videoDuration = ref(0); // 模拟的视频时长变量，20s
// 开始和结束时间
const calculateTimeRange = computed(() => {

    const pixelsPerSecond = videoDuration.value / 1100;
    const startTime = containerLeft.value * pixelsPerSecond;
    const endTime = (containerLeft.value + containerWidth.value) * pixelsPerSecond;
    return { startTime, endTime };
})

const closeModal = () => {
    dialog.value.closeModal();
}

defineExpose({
    showModal,
    closeModal
});
</script>

<template>
    <div class="ViewVideoModel">
        <baseModel ref="dialog" :contentWidth="'1148px'" :maskClosable="false" :destroyOnClose="true">
            <template #title>
                <div class="title_box">
                    <!-- {{ calculateTimeRange }}
                    {{ containerWidth }} -->
                    <span>视频信息 </span>
                </div>
            </template>
            <template #content>
                <div class="content">
                    <div class="video_box">
                        <video style="" playsinline="true" x5-playsinline="true" webkit-playsinline="true" tabindex="2"
                            mediatype="video" controls="controls" crossOrigin="anonymous" :src="videoUrl"
                            ref="showVideo">
                        </video>
                    </div>
                    <!-- <div class="canvasBox">
                        <canvas id="rulerCanvas" height="20" style="width: 100%; height: 30px;"></canvas>
                    </div> -->
                    <!-- 图片容器 -->
                    <div class="imgBox">
                        <canvas id="canvasElement" ref="canvasElement" style="height: 100%; width: 100%;"></canvas>
                        <!-- 抓手容器 -->
                        <div class="handles" :style="{ width: containerWidth + 'px', 'left': containerLeft + 'px' }">
                            <div class="handle_left handle" @mousedown="handelMousedown($event, 'left')"></div>
                            <div class="handle_right handle" @mousedown="handelMousedown($event, 'right')"></div>
                        </div>
                        <!-- <div class="img_item_box" v-for="item in resolveArr" :key="item.time">
                            <img :src="item.src" alt="">
                        </div> -->
                    </div>
                </div>
            </template>
            <template #footer>
                <div class="bottom">
                    <a-button class="btn" key="back" @click="reset" style="margin-right: 10px;">重置</a-button>
                    <a-button class="btn" key="submit" type="primary" :loading="loading" :disabled="disableSubmit"
                        @click="save">保存</a-button>
                </div>
            </template>
        </baseModel>
        <!-- 这个canvas元素用于绘制视频帧 -->
        <!-- <canvas id="canvasElement" ref="canvasElement" style="display: none;"></canvas> -->
        <!-- 这个video元素用于加载和控制视频 "https://cos.kuaijingai.com/upload/work_ai/20240305/65e6f4034cd8937599.mp4" -->
        <!-- crossOrigin="anonymous" -->
        <video id="videoElement" ref="videoElement" style="display: none;" controls preload="auto" src="" />
    </div>
</template>

<style lang="less" scoped>
.title_box {
    span {
        color: #1c1f23;
        font-size: 18px;
    }
}

.bottom {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .btn {
        border-radius: 4px;
        overflow: hidden;
    }
}

.content {

    // min-width: 1148px;
    .video_box {
        width: 100%;
        height: 560px;
        background-color: #000;
        margin-bottom: 10px;

        video {
            height: 100%;
            width: 100%;
        }
    }

    .imgBox {
        height: 36px;
        display: flex;
        justify-content: flex-start;
        position: relative;

        // 抓手
        .handles {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            // width: 100%;
            border: 2px solid #1664ff;
            background: rgba(190, 220, 255, .6);

            .handle {
                background: #1664ff;
                height: inherit;
                position: absolute;
                width: 12px;
                height: calc(100% + 4px);
                cursor: ew-resize;
            }

            .handle_left {
                left: -14px;
                top: -2px;
                border-radius: 6px 0px 0px 6px;
            }

            .handle_right {
                left: calc(100% + 2px);
                top: -2px;
                border-radius: 0px 6px 6px 0px;
            }
        }

        .img_item_box {
            display: inline-block;
            // height: 100%;
            flex: 1;
            display: flex;

            img {
                flex: 1;
                object-fit: cover;
            }
        }
    }

    .canvasBox {
        width: 100%;
    }
}
</style>